/*
 * LiquidBounce Hacked Client
 * A free open source mixin-based injection hacked client for Minecraft using Minecraft Forge.
 * https://github.com/CCBlueX/LiquidBounce/
 */
package net.ccbluex.liquidbounce.features.module.modules.exploit

import joptsimple.internal.Strings
import net.ccbluex.liquidbounce.event.EventTarget
import net.ccbluex.liquidbounce.api.minecraft.network.play.server.ISPacketTabComplete
import net.ccbluex.liquidbounce.event.PacketEvent
import net.ccbluex.liquidbounce.event.UpdateEvent
import net.ccbluex.liquidbounce.features.module.Module
import net.ccbluex.liquidbounce.features.module.ModuleCategory
import net.ccbluex.liquidbounce.features.module.ModuleInfo
import net.ccbluex.liquidbounce.utils.ClientUtils
import net.ccbluex.liquidbounce.utils.timer.TickTimer
import kotlin.collections.ArrayList
import java.util.Collections

@ModuleInfo(name = "Plugins", description = "Allows you to see which plugins the server is using.", category = ModuleCategory.EXPLOIT)
class Plugins: Module() {

    private val tickTimer = TickTimer()

    override fun onEnable() {
        if (mc.thePlayer == null)
            return

        mc.netHandler.addToSendQueue(classProvider.createCPacketTabComplete("/"))
        tickTimer.reset()
    }

    @EventTarget
    fun onUpdate(event: UpdateEvent) {
        tickTimer.update()

        if(tickTimer.hasTimePassed(20)) {
            ClientUtils.displayChatMessage("§cPlugins check timed out...")
            tickTimer.reset()
            state = false
        }
    }

    @EventTarget
    fun onPacket(event: PacketEvent) {
        if (classProvider.isSPacketTabComplete(event.packet)) {
            val s3APacketTabComplete: ISPacketTabComplete = event.packet.asSPacketTabComplete()

            val plugins = ArrayList<String>()
            val commands = s3APacketTabComplete.completions

            for (command1 in commands) {
                val command = command1.split(":")

                if (command.size > 1) {
                    val pluginName = command[0].replace("/", "")

                    if (!plugins.contains(pluginName))
                        plugins.add(pluginName)
                }
            }

            Collections.sort(plugins)

            if(!plugins.isEmpty())
                ClientUtils.displayChatMessage("§aPlugins §7(§8" + plugins.size + "§7): §c" + Strings.join(plugins.toArray(arrayOfNulls<String>(0)), "§7, §c"))
            else
                ClientUtils.displayChatMessage("§cNo plugins found.")
            state = false
            tickTimer.reset()
        }
    }
}
